﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;
using ScoutNET.Attributes;

namespace ScoutNET.Controllers
{
    public class LiensController : ApplicationController
    {
        private LinkRepository lr = new LinkRepository();
        private SectionRepository sr = new SectionRepository();

        #region Views
        public ActionResult Index(int? page)
        {
            ViewData["PageTitle"] = Resources.Liens_Index_Title;
            ViewData["PageDescription"] = Resources.Liens_Index_Description;

            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Liens_Index_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            bool validation = ((UserType)ViewData["UserType"] != UserType.Administrator);

            Int32 itemPage = 10;
            Double totalItems = Convert.ToDouble(lr.GetCountLinks(validation));
            Int32 totalPages = (Int32)Math.Ceiling(totalItems / itemPage);
            int pageID = (page == null || page == 0) ? 1 : (Int32)page;
            pageID = (page > totalPages) ? totalPages : pageID;
            Int32 skipItem = (pageID - 1) * itemPage;
            List<tSite_Link> lLinks = lr.GetLinks(skipItem, itemPage, validation);

            if (lLinks.Count > 0)
            {
                ViewData["TotalPages"] = totalPages;
                ViewData["TotalItems"] = lLinks.Count;
                ViewData["Page"] = pageID;

                return View("Index", lLinks);
            }
            else
            {
                ViewData["ErrorMessage"] = Resources.Liens_Index_NoItems;
                return View("Error");
            }
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [CaptchaValidator]
        [ValidateAntiForgeryToken()]
        public ActionResult Create(FormCollection fc, bool captchaValid)
        {
            if (ValidateLink(fc, captchaValid))
            {
                tSite_Link l = new tSite_Link();
                l.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                l.Title = fc["Title"].Trim();
                l.URL = fc["URL"].Trim();
                l.Validation = false;
                l.Description = fc["Description"].Trim();

                lr.InsertLink(l);
                lr.Save();

                Uri siteUrl = new Uri(ConfigurationManager.AppSettings["SiteUrl"]);
                string siteName = ConfigurationManager.AppSettings["SiteName"];

                string actionUrl = siteUrl + Url.Action("Link", new { controller = "Mail" });
                tSite_Section webmasterSection = sr.GetSectionsById(8);
                string email = ConfigurationManager.AppSettings["AdministratorMail"];

                string title = string.Empty;
                string body = Mail.GetMailHTML(actionUrl, Request.Form.ToString(), out title);
                body = body.AddUrlInHref(siteUrl).AddUrlInSrc(siteUrl);

                Mail.SendMail(email
                , title
                , body
                , webmasterSection.Email
                , webmasterSection.Section.UppercaseFirst() + " - " + siteName.UppercaseFirst());

                ViewData["ValidationMessage"] = Resources.Liens_Create_Validation;

                return View("Validation");
            }

            return View();
        }

        [Authorize(Roles = "C.U")]
        public ActionResult Delete(int id)
        {
            ViewData["ID"] = id;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "C.U")]
        public ActionResult Delete(FormCollection fc)
        {
            int ID = -1;
            if (int.TryParse(fc["ID"], out ID))
            {
                lr.DeleteLink(ID);
                lr.Save();
            }
            return View();
        }

        [Authorize(Roles = "C.U")]
        public ActionResult Edit(int id)
        {
            tSite_Link l = lr.GetLinkByID(id);
            if (l != null)
            {
                ViewData["PageTitle"] = Resources.Liens_Index_Title.Replace("[TITLE]", l.Title);
                ViewData["PageDescription"] = Resources.Liens_Index_Description.Replace("[TITLE]", l.Title);

                string[] saBreadcrumb = new String[3];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Liens_Index_Breadcrumb, "Default", "Index", "Liens", null, null);
                saBreadcrumb[2] = Resources.Liens_Edit_Breadcrumb.Replace("[TITLE]", l.Title);
                ViewData["Breadcrumb"] = saBreadcrumb;

                return View(l);
            }

            return View("Error404");
        }

        [HttpPost]
        [Authorize(Roles = "C.U")]
        public ActionResult Edit(FormCollection fc, int ID)
        {
            tSite_Link l = lr.GetLinkByID(ID);

            if (l != null)
            {
                ViewData["PageTitle"] = Resources.Liens_Edit_Title.Replace("[TITLE]", l.Title);
                ViewData["PageDescription"] = Resources.Liens_Edit_Description.Replace("[TITLE]", l.Title);

                string[] saBreadcrumb = new String[3];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Liens_Index_Breadcrumb, "Default", "Index", "Liens", null, null);
                saBreadcrumb[2] = Resources.Liens_Edit_Breadcrumb.Replace("[TITLE]", l.Title);
                ViewData["Breadcrumb"] = saBreadcrumb;

                if (ValidateLink(fc, true))
                {
                    l.Title = fc["Title"].Trim();
                    l.URL = fc["URL"].Trim();
                    l.Description = fc["Description"].Trim();
                    lr.Save();

                    ViewData["ValidationMessage"] = Resources.Liens_Edit_Validation;

                    return View("AdminValidation");

                }
                return View(l);
            }

            return View("Error404");
        }

        [Authorize(Roles = "C.U")]
        public ActionResult Validate(int id)
        {
            ViewData["ID"] = id;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "C.U")]
        public ActionResult Validate(FormCollection fc)
        {
            int ID = -1;
            if (int.TryParse(fc["ID"], out ID))
            {
                lr.ValidateLink(ID);
                lr.Save();
            }

            return View();
        }
        #endregion

        #region Methodes
        private bool ValidateLink(FormCollection fc, bool captchaValid)
        {
            ModelState.SetModelValue("Title", ValueProvider.GetValue("Title"));
            ModelState.SetModelValue("URL", ValueProvider.GetValue("URL"));
            ModelState.SetModelValue("Description", ValueProvider.GetValue("Description"));

            if (String.IsNullOrEmpty(fc["Title"].Trim()))
            {
                ModelState.AddModelError("Title", Resources.Contact_Index_Error_Firstname);
            }

            if (string.IsNullOrEmpty(fc["URL"].Trim()) || !Validation.IsURL(fc["URL"].Trim()))
            {
                ModelState.AddModelError("URL", Resources.Contact_Index_Error_Lastname);
            }

            if (String.IsNullOrEmpty(fc["Description"].Trim()))
            {
                ModelState.AddModelError("Description", Resources.Contact_Index_Error_Firstname);
            }

            if (!User.Identity.IsAuthenticated)
            {
                if (!captchaValid)
                {
                    ModelState.AddModelError(string.Empty, Resources.Contact_Index_Error_Captcha);
                }
            }

            return ModelState.IsValid;
        }
        #endregion
    }
}
